package org.flyby;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.flyby.api.dao.CartDao;
import org.flyby.api.dao.CodeTableDataDao;
import org.flyby.api.dao.UserDao;
import org.flyby.api.persistence.Cart;
import org.flyby.api.persistence.User;
import org.flyby.component.FlybyIndicatingAjaxSubmitLink;
import org.flyby.component.FlybyPage;

import static org.flyby.api.persistence.CodeTableData.DATA_CART_STATUS_START_SHOPPING;
import static org.flyby.api.persistence.CodeTableData.HEADER_CART_STATUS_CODE;

public class FlybyLoginPage extends FlybyPage {

    @SpringBean
    private UserDao userDao;

    @SpringBean
    private CartDao cartDao;

    @SpringBean
    private CodeTableDataDao codeTableDataDao;

    //Property models
    private String userName;
    private String password;

    public FlybyLoginPage() {

        Form form = new Form("form");

        add(form);
        form.add(new TextField<String>("userName", PropertyModel.<String>of(this, "userName")));
        form.add(new PasswordTextField("password", PropertyModel.<String>of(this, "password")));
        FlybyIndicatingAjaxSubmitLink button = new FlybyIndicatingAjaxSubmitLink("login") {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                super.onSubmit(target, form);

                User flybyUser = userDao.findByUserNameAndPassword(userName, password);
                if (flybyUser != null) {
                    this.setEnabled(false);
                    Cart cart = new Cart();
                    cart.setCartBarcode("1235");
                    cart.setUser(flybyUser);
                    cart.setTotalPrice((float) 0);
                    cart.setTotalWeight((float) 0);
                    cart.setTotalProducts(0);
                    cart.setCartStatus(codeTableDataDao.findByTableHeaderCodeAndItemCode(HEADER_CART_STATUS_CODE, DATA_CART_STATUS_START_SHOPPING));
                    cartDao.save(cart);

                    setResponsePage(new FlybyCartPage(cart));
                } else {
                    error("login failed");
                    target.add(((FlybyPage) getPage()).getFeedbackPanel());
                }

            }
        };
        form.add(button);


    }

}
